<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <script src="../libs/Cesium/Cesium.js"></script>
    <link href="../libs/Cesium/Widgets/widgets.css" rel="stylesheet">
    <style>
        #windLegend {
            position: absolute;
            bottom: 35px;
            left: 10px;
            background: rgba(38, 38, 38, 0.8);
            padding: 10px;
            border-radius: 5px;
            color: #fff;
            z-index: 999;
        }
        .legend-color {
            width: 20px;
            height: 20px;
            display: inline-block;
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <div id="cesiumContainer"></div>
    <div id="windLegend">
        <h4>风速 (m/s)</h4>
        <div id="colorLegend"></div>
    </div>
    <script>
        Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyODJkZWYzOC02YzViLTQwYTctYjVkNi00Y2U5OGNlYWQ1NmIiLCJpZCI6MjkwMTk0LCJpYXQiOjE3NDc5ODIyODl9.6l5vW-ugIxP2ZuUX_s0Wi1Yzn50hcAeB0FOIvIeIF5o';

        const viewer = new Cesium.Viewer('cesiumContainer', {
            timeline: false,
            animation: false,
            baseLayerPicker: false,
            geocoder: false,
            homeButton: false,
            sceneModePicker: false,
            navigationHelpButton: false
        });

        // 设置初始视角
        viewer.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(107.73, 7.89, 5000000),
            orientation: {
                heading: Cesium.Math.toRadians(0),
                pitch: Cesium.Math.toRadians(-90),
                roll: 0.0
            }
        });

        // 创建风场粒子系统
        const particleSystem = viewer.scene.primitives.add(new Cesium.ParticleSystem({
            modelMatrix: Cesium.Matrix4.IDENTITY.clone(),
            emitter: new Cesium.CircleEmitter(0.5),
            emitterModelMatrix: computeEmitterModelMatrix(),
            updateCallback: updateParticles,
            maxParticles: 10000,
            lifetime: 100,
            rate: 100,
            image: '../libs/SampleData/cesium_stripes.png',
            startScale: 0.5,
            endScale: 0.5,
            startColor: Cesium.Color.WHITE.withAlpha(0.7),
            endColor: Cesium.Color.WHITE.withAlpha(0.0)
        }));

        // 风速颜色映射
        const colorScale = [
            { value: 0, color: Cesium.Color.fromCssColorString("#000080") },
            { value: 5, color: Cesium.Color.fromCssColorString("#0000ff") },
            { value: 10, color: Cesium.Color.fromCssColorString("#00ffff") },
            { value: 15, color: Cesium.Color.fromCssColorString("#00ff00") },
            { value: 20, color: Cesium.Color.fromCssColorString("#ffff00") },
            { value: 25, color: Cesium.Color.fromCssColorString("#ff0000") }
        ];

        // 初始化图例
        initColorLegend();

        // 更新粒子位置函数
        function updateParticles(particle, dt) {
            // 此处需要连接实时数据API
            const position = particle.position;
            const cartographic = Cesium.Cartographic.fromCartesian(position);
            const windSpeed = getWindSpeed(cartographic.longitude, cartographic.latitude);
            
            // 根据风速设置颜色
            particle.color = getColorFromSpeed(windSpeed);
            
            // 更新粒子位置
            const direction = getWindDirection(cartographic.longitude, cartographic.latitude);
            particle.position = Cesium.Cartesian3.add(
                position,
                Cesium.Cartesian3.multiplyByScalar(direction, windSpeed * dt, new Cesium.Cartesian3()),
                particle.position
            );
        }

        // 实现颜色映射逻辑
        function getColorFromSpeed(speed) {
            for (let i = 1; i < colorScale.length; i++) {
                if (speed < colorScale[i].value) {
                    const ratio = (speed - colorScale[i-1].value) / (colorScale[i].value - colorScale[i-1].value);
                    return Cesium.Color.lerp(colorScale[i-1].color, colorScale[i].color, ratio, new Cesium.Color());
                }
            }
            return colorScale[colorScale.length-1].color;
        }

        // 初始化粒子发射器矩阵
        function computeEmitterModelMatrix() {
            const position = Cesium.Cartesian3.fromDegrees(107.73, 7.89);
            const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);
            return modelMatrix;
        }

        // 初始化颜色图例
        function initColorLegend() {
            const legendContainer = document.getElementById('colorLegend');
            colorScale.forEach(item => {
                const div = document.createElement('div');
                div.innerHTML = `
                    <div class="legend-color" style="background: ${item.color.toCssColorString()}"></div>
                    ${item.value}+
                `;
                legendContainer.appendChild(div);
            });
        }

        // 从本地API获取真实风场数据
        let windData = null;
        
        async function fetchWindData() {
            try {
                const response = await fetch('../data/wind_850hpa.json');
                windData = await response.json();
                console.log('风场数据更新成功：', new Date().toLocaleString());
            } catch (error) {
                console.error('数据获取失败：', error);
            }
        }

        // 插值获取指定位置的风速风向
        function getWindSpeed(lon, lat) {
            if (!windData) return 0;
            
            // 标准化经纬度到数据网格
            const gridSize = 0.25;
            const x = Math.floor((lon + 180) / gridSize);
            const y = Math.floor((lat + 90) / gridSize);
            
            return windData[x]?.[y]?.speed || 0;
        }

        function getWindDirection(lon, lat) {
            if (!windData) return new Cesium.Cartesian3(0, 0, 0);
            
            const gridSize = 0.25;
            const x = Math.floor((lon + 180) / gridSize);
            const y = Math.floor((lat + 90) / gridSize);
            const angle = windData[x]?.[y]?.direction || 0;
            
            return new Cesium.Cartesian3(
                Math.cos(angle),
                Math.sin(angle),
                0
            );
        }

        // 初始化加载数据并启动定时更新
        fetchWindData().then(() => {
            setInterval(async () => {
                await fetchWindData();
                viewer.scene.primitives.remove(particleSystem);
                particleSystem = viewer.scene.primitives.add(new Cesium.ParticleSystem({
                    ...particleSystem,
                    emitterModelMatrix: computeEmitterModelMatrix()
                }));
            }, 600000); // 每10分钟更新一次
        });
    </script>
</body>
</html>
